<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="isreFreshLoading"
      @refresh="onRefresh"
      :success-text="refreshSuccessText"
      success-duration="1500"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <ArticleItem
          v-for="(item, index) in list"
          :key="index"
          :article="item"
        ></ArticleItem>
        <!-- <van-cell
          v-for="(item, index) in list"
          :key="index"
          :title="item.title"
        /> -->
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticle } from "@/api/article";
import ArticleItem from "@/components/article-item";

export default {
  props: {
    channel: {
      type: Object,
      require: true,
    },
  },
  components: {
    ArticleItem,
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      error: false,
      isreFreshLoading: false,
      refreshSuccessText: "更新成功",
    };
  },
  methods: {
    async onLoad() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      try {
        const { data } = await getArticle({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
        });
        // console.log(data);
        // // 模拟报错
        // if (Math.random() > 0.5) {
        //   JSON.parse("dafasefass");
        // }
        const { results } = data.data;
        this.list.push(...results);
        this.loading = false;
        if (results.length) {
          this.timestamp = data.data.pre_timestamp;
        } else {
          this.finished = false;
        }
      } catch (err) {
        // console.log("获取失败", err);
        this.error = true;
        this.loading = false;
      }
    },
    // 下拉
    async onRefresh() {
      try {
        const { data } = await getArticle({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
        });
        // 模拟报错
        // if (Math.random() > 0.2) {
        //   JSON.parse("dafasefass");
        // }
        const { results } = data.data;
        this.list.unshift(...results);
        this.isreFreshLoading = false;
        this.refreshSuccessText = `更新成功，更新了${results.length}条数据`;
      } catch (err) {
        // console.log("请求失败", err);
        this.isreFreshLoading = false;
        this.refreshSuccessText = "刷新失败";
      }
    },
  },
};
</script>

<style scoped lang="less">
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>
